﻿using MQTTEntity;
using MQTTnet;
using System.Text;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace MQTTPublisher
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await Publish_Application_Message();
        }
        public static async Task Publish_Application_Message()
        {
            var mqttFactory = new MqttClientFactory();

            var mqttClient = mqttFactory.CreateMqttClient();
            var mqttClientOptions = new MqttClientOptionsBuilder()
                .WithTcpServer("127.0.0.1")
                .Build();

            //客户端向服务器发起连接
            await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
            Console.WriteLine("发布者进程...");
            Console.WriteLine("发布者连接MQTT服务器成功...");

string data;
while (true)
{
    Console.Write("请输入需要发送的消息:");
    data = Console.ReadLine();
    data = "time:" + DateTime.Now.ToString("yyyy-MM-dd HH:MM:ss") + " msg:" + data;
    byte[] bytes = MessageBuilder<string>.Create()
        .WithCode(200)
        .WithMsg("msg")
        .WithData(data)
        .Build();

    var applicationMessage = new MqttApplicationMessageBuilder()
        .WithTopic("mytopic")
        .WithPayload(bytes)
        .Build();
    var result = await mqttClient.PublishAsync(applicationMessage, CancellationToken.None);
}
        }
    }
}
